<template>
  <draggable
    v-model="draggableList"
    group="people"
    @start="drag = true"
    @end="drag = false"
    @change="dragChange"
    ghost-class="ghost"
    handle=".mover"
    filter=".unmover"
    draggable=".item"
    item-key="id"
  >
    <template #item="{ element }">
      <div class="dragg_item" :class="{ item: !element.disabled, mover: !element.disabled, unmover: element.disabled }">
        <div class="header">
          <el-icon v-if="!element.disabled"><Sort /></el-icon>
        </div>
        <div class="body">
          {{ element.name }}
        </div>
      </div>
    </template>
  </draggable>
</template>
<script setup lang='ts'>
import { ref, reactive, getCurrentInstance, withDefaults, watch, defineEmits } from "vue";
import draggable from "vuedraggable";
import { Idraggable } from "./interface.ts";

//实例
const { proxy } = getCurrentInstance();

// 定义可发出的事件类型
const $emit = defineEmits(["dragChange"]);

// 定义组件接收的props
const props = withDefaults(defineProps<{ list: Idraggable[] }>(), {
  list: [] // 默认的可拖拽列表为空数组
});

// 参与拖拽状态的控制
const drag = ref<Boolean>(false);

// 维护一个本地的可拖拽列表状态
const draggableList = ref<Idraggable[]>(props.list);

/**
 * 触发dragChange事件，将当前的可拖拽列表发送给父组件。
 */
const dragChange = () => {
  $emit("dragChange", draggableList.value);
};

// 监听props.list的变化，同步更新draggableList的值
watch(
  () => props.list,
  newVal => {
    draggableList.value = newVal;
  }
);
</script>
<style lang='scss' scoped>
.dragg_item {
  display: flex;
  justify-content: start;
  justify-items: center;
  position: relative;
  min-height: 30px;
  padding: 5px;
  border: 1px solid #e6e6ee;
  margin-bottom: 10px;
  background: #fff;
  border-radius: 2px;
  &:hover {
    cursor: move;
  }
  .header {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 0px;
    top: 0px;
    height: 100%;
    width: 30px;
    color: #a0a3a9;
  }
  .body {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #303133;
  }
  &.unmover:hover {
    cursor: unset;
  }
  &.mover.sortable-chosen {
    cursor: move;
    border: 1px solid var(--el-color-primary);
    .header {
      color: var(--el-color-primary);
    }
  }
  &.ghost { 
    opacity: 0.6; 
    border: 1px dashed var(--el-color-primary) !important; 
    .body {
      color: var(--el-color-primary) !important;
    }
  }
}
</style>
